package com.efounder.activity;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.broadcast.BroadCastutil;
import com.efounder.forwechat.BaseApp;
import com.efounder.fragment.MoreMenuFrag;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.MyStaticWebView;
import com.efounder.util.StorageUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.sliding.AbBottomTabView;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.view.titlebar.AbTitleBar;
import com.efounder.widget.ESPWebView.JsToandroidCallBack;
import com.efounder.widget.TabBarNew;
import com.efounder.widget.TabBarNew.OnCurrentTabChangedListener;
import com.pansoft.resmanager.ResFileManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

//import com.pansoft.xmlparse.MenuList;
//import com.pansoft.xmlparse.MenuParse;

/**
 * 底部 activity
 */
@SuppressWarnings("unused")
public class TabBottomActivityWithCache extends AbActivity implements
        OnCurrentTabChangedListener {

    private AbBottomTabView mBottomTabView;
    private List<Drawable> tabDrawables = null;
    private AbTitleBar mTitleBar;
    List<String> tabTexts;
    private StorageUtil storageUtil;
    FragmentManager fragmentManager;
    public RadioGroup rg;
    RadioButton rb1, rb2, rb3, rb4;

    /**
     * 记录按下返回键的时间
     */
    private long firstime;

    private List<StubObject> mainMenus; // 主菜单
    private List<StubObject> defaultMenus;
    public static final String KEY_MENU_ROOT = "menuRoot";
    private Fragment fragment;
    StubObject mainMenuItem;

    private RadioGroup rgs;
    public List<Fragment> fragments = new ArrayList<Fragment>();

    public Fragment[] cachedFragments; // 缓存主菜单对应的Fragments

    private AbBottomBar mBottomBar = null;

    /**
     * 当前Tab页面索引
     */
    public int currentTab;

    /**
     * 默认展示页
     */
    private final static int inittab = 0;
    private FragmentManager fm;
    static TabBottomActivityWithCache mySelf;
    private Fragment preprocessedFrag;
    /**
     * 底部按钮是否正在显示状态
     */
    private boolean isShowing;
    private TabBarNew tb;
    public static final String TAG = "TabBottomActivity";


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.tab_bottom_n);
        BaseApp.actManager.putActivity(TAG, this);
        storageUtil = new StorageUtil(getApplicationContext(), "storage");
        mBottomBar = this.getBottomBar();
		 /*Thread t = new Thread(new Runnable(){  
	            public void run(){  
	            
	            }});  
	        t.start();  */
        //initWebview();
        MyStaticWebView.setContext(this);
        //initView();
        List<StubObject> listObj = (List<StubObject>) getIntent().getSerializableExtra("listobj");
        mainMenus = listObj;
        // 设置默认显示的标签页
        fm = getSupportFragmentManager();
        makeMainMenu();
        initData();


        getTitleBar().setVisibility(View.GONE);


    }

    private void initWebview() {
        // TODO Auto-generated method stub
        MyStaticWebView.newInstance(TabBottomActivityWithCache.this
                .getApplicationContext());
        //Log.i("TimeCheck","登录初始化webview所用时间————————"+(System.currentTimeMillis() - currentTime));
        MyStaticWebView.getWv().setJsToandroidCallBack(
                new JsToandroidCallBack() {

                    @Override
                    public void html5initover() {

                    }
                });
        MyStaticWebView.getWv().setEspContext(this);
        //storageUtil.putBoolean("initweb", true);
    }

    private void initData() {
        mySelf = this;
        isShowing = true;
    }

    @Override
    public void onBackPressed() {

        if (fm.getBackStackEntryCount() != 0) {
            fm.popBackStack();
        } else {

            //long secondtime = System.currentTimeMillis();
            //if (secondtime - firstime > 2000) {

            new QMUIDialog.MessageDialogBuilder(this)
                    .setMessage("您确定要退出?")
                    .addAction(getString(R.string.common_text_confirm), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            try {
                                BroadCastutil.getinstance().unregisterBroadcastList(TabBottomActivityWithCache.this);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.exit(0);
                        }
                    })
                    .addAction(getString(R.string.common_text_cancel), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    }).show();
            //Toast.makeText(TabBottomActivity.this, "再按一次返回键退出",
            //	Toast.LENGTH_SHORT).show();

            //firstime = System.currentTimeMillis();
            //}
			/*else {
				try {
					BroadCastutil.getinstance().unregisterBroadcastList(this);
				} catch (Exception e) {
					e.printStackTrace();
				}
				BaseApp.actManager.closeAllActivity();
			//	System.exit(0);
				super.onBackPressed();
			}*/
        }
    }

    /**
     * 初始化UI
     */
    private void initView() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                // 后台下载并解析菜单, 并且获取主菜单 PACKAGE_DIR
                File file = new File(ResFileManager.PACKAGE_DIR + "/"
                        + "Tab_Menu.xml");
//				MenuParse.getMenu(file);
//				mainMenuList = MenuList.getMenuList(KEY_MENU_ROOT);
//				defaultMenus = MenuList.getMenuList("DefaultOpenMenu");
                mainMenus = Registry.getRegEntryList(KEY_MENU_ROOT);
                defaultMenus = Registry.getRegEntryList("DefaultOpenMenu");
                if (mainMenus == null && defaultMenus != null) {
                    mainMenus = defaultMenus;
                }
                return null;
            }

            protected void onPostExecute(Void result) {
                // 加载完主菜单之后调用, 用于显示主菜单等操作
                makeMainMenu();
            }

        }.execute();

    }

    /**
     * 加载完主菜单之后调用, 生存主菜单布局
     */
    private void makeMainMenu() {
        if (mainMenus == null) {
            Toast.makeText(this, ResStringUtil.getString(R.string.common_text_http_request_data_fail), Toast.LENGTH_SHORT).show();
            this.finish();
            return;
        }
        if (mainMenus.size() > TabBarNew.MAX_BOTTOM_ITEMS) {
            cachedFragments = new Fragment[mainMenus.size() + 1];
        } else
            cachedFragments = new Fragment[mainMenus.size()];
        loadBottomBar(mainMenus);
    }

    private void loadBottomBar(List<StubObject> espMenuList) {
        mBottomBar.setVisibility(View.VISIBLE);
        tb = new TabBarNew(this, espMenuList);
        mBottomBar.addView(tb);
        tb.setOnCurrentTabChangedListener(this);
        currentTab = inittab;
        Fragment firstFrag = initAndCacheFragment(inittab);
        showFragment(firstFrag);
    }

    @Override
    public void onCurrentTabChanged(int index) {
        showFragment(index);
    }

    public void showFragment(int index) {
        Log.i("", "test-----====================TabBottomActivity: onCurrentTabChanged:位置：" + index);
        // 缓存并显示fragment
        Fragment fragToShow = null;
        if (cachedFragments[index] != null) { // 取缓存
            fragToShow = cachedFragments[index];
        } else {
            if (index == mainMenus.size()) {
                List<StubObject> menuListTemp = new ArrayList<StubObject>();
                for (int i = TabBarNew.BOTTOM_ITEM; i < mainMenus.size(); i++) {
                    menuListTemp.add(mainMenus.get(i));
                }
                fragToShow = new MoreMenuFrag(menuListTemp, this,
                        TabBarNew.BOTTOM_ITEM);
                cachedFragments[index] = fragToShow; // 缓存
            } else {
                fragToShow = initAndCacheFragment(index);
            }
        }
        FragmentTransaction ft = obtainFragmentTransaction(index);
        getCurrentFragment().onPause(); // 暂停当前tab
        if (fragToShow.isAdded()) {
            fragToShow.onStart(); // 启动目标tab的onStart()
        } else {
            ft.add(R.id.mainContent, fragToShow);
        }
        showTab(index); // 显示目标tab
        ft.commit();

    }

    /**
     * 创建并且缓存Fragment
     *
     * @param index
     */
    private Fragment initAndCacheFragment(int index) {
        BaseFragment frag = null;
        StubObject mainMenuItem = (StubObject) mainMenus.get(index);

        // frag = com.efounder.util.AbFragmentManager.getFragment(mainMenuItem);
        AbFragmentManager ab = new AbFragmentManager(this);
        // 根据viewtype的类型得到
        frag = ab.getFragment(mainMenuItem);
        frag.setAlone(false);
        cachedFragments[index] = frag; // 缓存
        return frag;
    }

    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // 设置切换动画
		/*if (index > currentTabIndex) {
			ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out);
		} else {
			ft.setCustomAnimations(R.anim.slide_right_in,
					R.anim.slide_right_out);
		}*/
        return ft;
    }

    public Fragment getCurrentFragment() {
        return cachedFragments[currentTab];
    }

    /**
     * 切换TAB(先隐藏，后显示)
     */
    private void showTab(int index) {
        FragmentTransaction ft = obtainFragmentTransaction(index);
        Fragment willShowFragment = cachedFragments[index];
        Fragment willHideFragment = cachedFragments[currentTab];
        if (willHideFragment != null) {
            ft.hide(willHideFragment);
        }

        if (willShowFragment != null) {
            ft.show(willShowFragment);
        }
        ft.commit();
        currentTab = index; // 更新目标tab为当前tab
    }

    /**
     * 显示fragment
     */
    private void showFragment(Fragment frag) {
        FragmentTransaction tra = fm.beginTransaction();
        tra.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

        tra.replace(R.id.mainContent, frag);
        tra.commit();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    // ----------------提供接口--------------------
    public static TabBottomActivityWithCache getInstance() {
        return mySelf;
    }

/*	public void showForms(StubObject data) {
		Intent intent = new Intent(this, FormsActivity.class);
		intent.putExtra("data", data);
		startActivity(intent);
	}*/

    public void jumpAndStoreStack(Fragment frag) {
        if (frag == null) {
            return;
        }
        FragmentTransaction trasaction = fm.beginTransaction();
        trasaction.add(R.id.mainContent, frag);
        trasaction.addToBackStack(null);
        trasaction.commit();
    }

    public void popBackStack() {
        fm.popBackStack();
    }

    public TabBarNew getTb() {
        return tb;
    }

    public interface refreshfordefineMenu {

    }


}
